#include <input_manager.h>#include <draw.h>#include <config.h>#include <stdlib.h>#include <tslib.h>static struct tsdev *g_ptTs;static int g_iXres;static int g_iYres;static T_InputOpr g_tTouchscreenInputOpr;static int TouchscreenDeviceInit(void){	char *tTsdevice = NULL;

	if( (tTsdevice = getenv("TSLIB_TSDEVICE")) != NULL )
	{
		g_ptTs = ts_open(tTsdevice,1);
	}
	else
	{
		g_ptTs = ts_open("/dev/event1", 1);
	}

	if (!g_ptTs)
	{
		printf("ts_open error\n");
		return -1;
	}

	if (ts_config(g_ptTs)) {
		printf("ts_config error\n");
		return -1;
	}	if(GetDisplayResolution(&g_iXres, &g_iYres))	{		printf("GetDisplayResolution in touchscreen error\n");		return -1;	}	g_tTouchscreenInputOpr.iFd = ts_fd(g_ptTs);	
	return 0;}
static int TouchscreenDeviceExit(void){
	return 0;}
static int isOutof500Ms(struct timeval *ptPreTime, struct timeval *ptNowTime){
	int iPreMs;
	int iNowMs;

	iPreMs = ptPreTime->tv_sec*1000 + ptPreTime->tv_usec/1000;
	iNowMs = ptNowTime->tv_sec*1000 + ptNowTime->tv_usec/1000;

	return (iNowMs > iPreMs + 500);}
static int TouchscreenGetInputEvent(PT_InputEvent ptInputEvent){	struct ts_sample tSamp;
	int iRet;

	static struct timeval tPreTime;
	
	iRet = ts_read(g_ptTs, &tSamp, 1);
	
	if (iRet < 0) 
	{
		DEG_PRINTF("ts_read error\n");
		return -1;
	}
	if(isOutof500Ms(&tPreTime, &tSamp.tv))
	{		tPreTime = tSamp.tv;		ptInputEvent->tTime = tSamp.tv;		ptInputEvent->iType = INPUT_TYPE_TOUCHSCREEN;		
		if(tSamp.y < g_iYres/3)		{			ptInputEvent->iVal = INPUT_VALUE_UP;		}		else if(tSamp.y > 2*g_iYres/3)		{			ptInputEvent->iVal = INPUT_VALUE_DOWN;		}		else		{			ptInputEvent->iVal = INPUT_VALUE_UNKNOWN;		}		return 0;
	}	else	{		return -1;	}
	//return 0;}

static T_InputOpr g_tTouchscreenInputOpr = {
	.name = "touchscreen",
	.DeviceInit = TouchscreenDeviceInit,
	.DeviceExit = TouchscreenDeviceExit,
	.GetInputEvent = TouchscreenGetInputEvent,};
int TouchscreenRegister(void){	return RegisterInputOpr(&g_tTouchscreenInputOpr);}
